/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.uoc.tdp.pac4.admn;

import edu.uoc.tdp.pac4.beans.Stock;
import edu.uoc.tdp.pac4.cliente.Principal;
import edu.uoc.tdp.pac4.comun.Enumerados.PerfilEnum;
import edu.uoc.tdp.pac4.comun.GestorAdministrativaInterface;
import edu.uoc.tdp.pac4.comun.PAC4Exception;
import edu.uoc.tdp.pac4.comun.Utils;
import edu.uoc.tdp.pac4.i18n.TDSLanguageUtils;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.Locale;
import javax.swing.JInternalFrame;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author mirica
 */
public class GestionStock extends JInternalFrame {

    private GestorAdministrativaInterface conexion;
    
    private final String URL = "localhost";
    private final String JNDI_NAME ="Serv_Administrativa";
    private final int PORT = 1099;    
    
    private ModelStock modelo;
    private int IdTaller = 0;
    
    /**
     * Creates new form NewJFrame
     */
    public GestionStock(GestorAdministrativaInterface conn) {
        if(conn!=null)
            conexion=conn;          
        
        initComponents();
     
        conectarServerRMI();
       
        seleccionDeIdioma();
        inicializarControles();
        
        if(Principal.currentUser.getID() > 0) {
            IdTaller = Principal.currentUser.getTaller().getId();
            getStockTaller(IdTaller);
        }
    }
    
    private void conectarServerRMI() {
        try {
            Registry registry = LocateRegistry.getRegistry(URL,PORT);
            this.conexion = (GestorAdministrativaInterface)registry.lookup(JNDI_NAME);
        } catch (NotBoundException e) {
            Utils.shownError(TDSLanguageUtils.getMessage("Admin.ErrorRMI"));
            System.exit(0);
        } catch (RemoteException e) {
            Utils.shownError(TDSLanguageUtils.getMessage("Admin.ErrorRMI"));
            System.exit(0);
        } catch (Exception e) {
            Utils.shownError(TDSLanguageUtils.getMessage("Aplication.ExcpGeneral"));
            System.exit(0);
        }    
    }   
    
    private void getStockTaller(int idTaller) {
        try {
           String[] columnas = {TDSLanguageUtils.getMessage("Admin.Stock.Codigo"), TDSLanguageUtils.getMessage("Admin.Stock.Descripcion"), 
               TDSLanguageUtils.getMessage("Admin.Stock.Unidades"), TDSLanguageUtils.getMessage("Admin.Stock.PVP"), 
               TDSLanguageUtils.getMessage("Admin.Stock.PVD")};
           
           int fila = -1;
           int numFilas = conexion.obtenerPiezas().size();
                   
           Object[][] data = new Object[numFilas][5];
           ArrayList<Stock> listaStock = conexion.obtenerStock(idTaller);
           for (Stock stock : listaStock) {
                fila++;

                data[fila][0] = stock.getCodiPeca();
                data[fila][1] = stock.getDescripcio();
                data[fila][2] = stock.getStock();
                data[fila][3] = stock.getPvp();
                data[fila][4] = stock.getPvd();
            }
           
           modelo = new ModelStock(data, columnas);
           tblStock.setModel(modelo);
           
        } catch (RemoteException ex) {
            Utils.shownError(TDSLanguageUtils.getMessage("Admin.ErrorRMI"));
        } catch (PAC4Exception ex) {
            Utils.shownError(TDSLanguageUtils.getMessage("Admin.Error"));
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblStock = new javax.swing.JTable();
        lblTituloStock = new javax.swing.JLabel();
        btnCerrar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        tblStock.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tblStock);

        lblTituloStock.setFont(new java.awt.Font("Calibri", 3, 14)); // NOI18N
        lblTituloStock.setForeground(new java.awt.Color(51, 51, 255));
        lblTituloStock.setText("GESTIÓN STOCK");

        btnCerrar.setText("CERRAR");
        btnCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCerrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 601, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblTituloStock)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnCerrar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTituloStock)
                .addGap(22, 22, 22)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 82, Short.MAX_VALUE)
                .addComponent(btnCerrar)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCerrarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GestionStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GestionStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GestionStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GestionStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GestionStock(null).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCerrar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblTituloStock;
    private javax.swing.JTable tblStock;
    // End of variables declaration//GEN-END:variables

    private void seleccionDeIdioma() {
        Locale localLocale = new Locale("es", "ES");
        TDSLanguageUtils.setDefaultLanguage("i18n/messages");
    }
   
    private void inicializarControles() {
        lblTituloStock.setText(TDSLanguageUtils.getMessage("Admin.Stock.Titulo"));
        btnCerrar.setText(TDSLanguageUtils.getMessage("Admin.Stock.Cerrar"));
    }
    
    public class ModelStock extends DefaultTableModel
    {
        private ModelStock(Object[][] data, String[] columnas) {
            this.setDataVector(data, columnas);
            
            this.addTableModelListener(new TableModelListener() {
                @Override
                public void tableChanged(TableModelEvent e) {
                    //Actualizar los cambios
                    int fila = e.getFirstRow();
                    int columna = e.getColumn();
                    if ((fila > -1) && (columna > -1)) {
                        try {
                            int unidades = Integer.parseInt(modelo.getValueAt(fila, 2).toString());
                            int codigo = Integer.parseInt(modelo.getValueAt(fila, 0).toString());
                            conexion.ActualizarStock(codigo, IdTaller, unidades);
                        } catch (RemoteException ex) {
                            Utils.shownError(TDSLanguageUtils.getMessage("Admin.ErrorRMI"));
                        } catch (PAC4Exception ex) {
                            Utils.shownError(TDSLanguageUtils.getMessage("Admin.Error"));
                        } catch (Exception ex) {
                            Utils.shownError(TDSLanguageUtils.getMessage("Admin.Stock.UNIDADES_FORMATO_INCORRECTO"));
                        }
                        finally {
                            //Cargar de nuevo la tabla
                            getStockTaller(IdTaller);
                        }
                    }
                }
            });
        }
        
        @Override
        public boolean isCellEditable (int row, int column)
        {
            if(Principal.currentUser.getPerfil().getId() == PerfilEnum.ADMINISTRADOR.getPerfil() || 
               Principal.currentUser.getPerfil().getId() == PerfilEnum.ADMINISTRATIVO.getPerfil()) 
                return true;
            return false;
        }
    }
}

